﻿/// <reference path="stringbuilder.js" />
/// <reference path="layer/layer.js" />

/**
 * 精确到小数位，兼容IE
 * @param {} s 
 * @returns {} 
 */
Number.prototype.toFixed = function (s) {
    return (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();
};
//只允许输入整数
function onlyInputInt(obj) {
    obj.value = obj.value.replace(/[^0-9]/g, '');
    if (obj.value === "") {
        obj.value = "";
    }
    else if (obj.value.replace(/0/g, "") !== "") {
        obj.value = replaceAllInsignificanceZero(obj.value);
    } else {
        obj.value = 0;
    }
}

//只允许输入数字
/*
 * @param {} obj 
 * @param {精确到几位数} precisioLen 
 * @returns {} 
 */
function onlyInputDecimal(obj, precisioLen) {
    //把所有的非数字和小数点全部替换为空， 然后把第一个小数点替换为一个特殊字符，然后把其他所有的小数点替换为空，然后把特殊字符替换为小数点
    obj.value = obj.value.replace(/[^0-9.]/g, '').replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    //如果以小数点开始的数字，前面加一个0
    if (obj.value.indexOf('.') == 0)
        obj.value = "0" + obj.value.toString();
    //替换掉所有没有意义数字前面的0，
    if (obj.value === "") {
        obj.value = "";
    }
    else if (obj.value.replace(/0/g, "") !== "") {
        obj.value = replaceAllInsignificanceZero(obj.value);
    } else {
        obj.value = 0;
    }
    if (precisioLen && !isNaN(precisioLen)) {
        var index = obj.value.indexOf('.');
        if (index <= 0)
            return;
        var startIndexToEndLen = obj.value.substring(index).length;

        if (startIndexToEndLen > precisioLen)
            obj.value = obj.value.substring(0, obj.value.length + (precisioLen + 1 - startIndexToEndLen));
    }
}

//替换掉无意义的0
function replaceAllInsignificanceZero(value) {
    //如果没有小数位，并且是以0开头的（如0011），把0替换掉，或者以0开头小数点的位置大于1的（如00.11）
    if ((value.indexOf('0') == 0 && value.indexOf('.') < 0) || (value.indexOf('0') == 0 && value.indexOf('.') > 1)) {
        value = value.substr(1, value.length);
        value = replaceAllInsignificanceZero(value);
    }
    return value;
}


var bootStrapOkIncon = "<i class='icon-ok'></i>";
var bootStrapRemoveIncon = "<i class='icon-remove'></i>";
function getFormatDate(date, fmt) {
    if (!fmt || fmt == "")
        fmt = "yyyy-MM-dd HH:mm:ss";
    if (!date)
        return "";
    if (typeof (date) == "string")
        return new Date(Number(date.replace(/\D/g, ''))).Format(fmt);
    else
        return date.Format(fmt);
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

String.prototype.trim = function (char, type) {
    if (char) {
        if (type == 'left') {
            return this.replace(new RegExp('^\\' + char + '+', 'g'), '');
        } else if (type == 'right') {
            return this.replace(new RegExp('\\' + char + '+$', 'g'), '');
        }
        return this.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
    }
    return this.replace(/^\s+|\s+$/g, '');
};


function getTruncateStr(str, len, lable) {
    if (!str) return '';
    var result;
    len = len || 20;
    if (str.length > len) {
        result = str.substr(0, len) + "...";
        if (lable) {
            var sb = new StringBuilder();
            sb.Append("<");
            sb.Append(lable);
            sb.Append(" title='");
            sb.Append(str);
            sb.Append("' class='break-word-all'>");
            sb.Append(result);
            sb.Append("</");
            sb.Append(lable);
            sb.Append(">");
            result = sb.ToString();
        }
    }
    return result || str;
}

$(function () {
    var requiredTds = $("form[class='form-horizontal']").find("[required],[validate*='required:true']");
    setRequiredAsterisk(requiredTds);

    var elements = $("body").find("*[class*='disabled-element']");
    setElementsDisabled(elements);

    $("textarea").each(function () {
        try {
            autoTextarea(this, 10, 300);
        } catch (e) {

        }
    });
});

//添加星号
function setRequiredAsterisk(elements) {
    try {
        if (elements) {
            for (var i = 0; i < elements.length; i++) {
                var requiredElement = elements[i];
                if ($(requiredElement).parent().is('td')) {
                    var tdElement = $(requiredElement).parent().prev().find("label").first(); //找到当前元素前面一个div的上一个label(第一个）
                    if (tdElement.find("[class=asterisk]").length < 1) { //如果加了，就不再加
                        $(tdElement).html("<span class='asterisk'>*</span>" + $(tdElement).html()); //设置其HTML;
                    }
                } else if ($(requiredElement).parent().is('div')) {
                    var prevElement = $(requiredElement).parent().parent().find("label"); //找到当前元素前面一个div的上一个label
                    if (prevElement.find("[class=asterisk]").length < 1) { //如果加了，就不再加
                        $(prevElement).html("<span class='asterisk'>*</span>" + $(prevElement).html()); //设置其HTML;
                    }
                }
            }
        }
    } catch (e) {
        console.log(e);
    }
}
/**
 * 富文本自适应高度
 * @param {元素} elem 
 * @param {初始高度加高高度} extra 
 * @param {最高高度} maxHeight 
 * @returns {null} 
 */
var autoTextarea = function (elem, extra, maxHeight) {
    var isFirst = true;
    var elemID = "";
    extra = extra || 0;
    var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
    isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
            addEvent = function (type, callback) {
                elem.addEventListener ?
                        elem.addEventListener(type, callback, false) :
                        elem.attachEvent('on' + type, callback);
            },
            getStyle = elem.currentStyle ? function (name) {
                var val = elem.currentStyle[name];

                if (name === 'height' && val.search(/px/i) !== 1) {
                    var rect = elem.getBoundingClientRect();
                    return rect.bottom - rect.top -
                            parseFloat(getStyle('paddingTop')) -
                            parseFloat(getStyle('paddingBottom')) + 'px';
                };

                return val;
            } : function (name) {
                return getComputedStyle(elem, null)[name];
            },
            minHeight = parseFloat(getStyle('height'));

    elem.style.resize = 'none';

    var change = function () {

        var scrollTop, height,
                padding = 0,
                style = elem.style;

        if (elem._length === elem.value.length) return;
        elem._length = elem.value.length;

        if (!isFirefox && !isOpera) {
            padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
        };
        scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

        elem.style.height = minHeight + 'px';
        if (elem.scrollHeight > minHeight) {
            if (maxHeight && elem.scrollHeight > maxHeight) {
                height = maxHeight - padding;
                style.overflowY = 'auto';
            } else {
                height = elem.scrollHeight - padding;
                style.overflowY = 'hidden';
            };
            if (isFirst || elemID != elem.id) {
                height += 15;
                isFirst = false;
                elemID = elem.id;
            }
            style.height = height + extra + 'px';
            scrollTop += parseInt(style.height) - elem.currHeight;
            document.body.scrollTop = scrollTop;
            document.documentElement.scrollTop = scrollTop;
            elem.currHeight = parseInt(style.height);
        };
    };

    addEvent('propertychange', change);
    addEvent('input', change);
    addEvent('focus', change);
    addEvent('blur', change);
    change();
}

function setElementsDisabled(elements) {
    try {
        if (elements) {
            elements.each(function () {
                if (this.type == "text" || this.type == "textarea")
                    $(this).focus(function () {
                        this.blur();
                    });
                else {
                    $(this).attr("disabled", "disabled");
                }
            });
        }
    } catch (e) {

    }
}

//按回车搜索 by yishuaijun
window.onkeydown = function (e) {
    try {
        if (e.keyCode == 13) {
            search();
            if (e && e.preventDefault)
                e.preventDefault();
            else
                window.event.returnValue = false;
            return false;
        }
    } catch (e) {

    }
    return true;
}

function showBSModalDialog(id, width, height) {
    width = width || 400;
    $('#' + id).width(width).height(height).css({
        'top': function () {
            return (($(top.window).height() - this.height) / 3);
        },
        'left': function () {
            return (($(top.window).width() - width + 200) / 2);
        },
        'overflow': 'hidden'
    }).modal({
        backdrop: 'static'
    }).find(" > div").css({
        'margin-left': 0
    });
}

function showLayerOpen(title, url, width, height) {
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.8,
        area: [width, height],
        content: url //iframe的url
    });
}

function clearForm(formId) {
    try {
        document.getElementById(formId).reset();
    } catch (e) {

    }
}

function SyncAideRepairInfo(warrantyId) {
    var indx = layer.load();
    $.ajax({
        type: "POST",
        url: "/Common/SyncAideRepairInfo",
        data: { warrantyId: warrantyId },
        success: function (data) {
            layer.close(indx);
            //alert(data.result);
            if (data.result) {
                layer.msg("success");
            }
        },
        error: function (error) {
            console.log(error);
            layer.close(indx);
        }
    });
}
function InitTime() {
    return '<a href="#" class="atip" target="mainFrame" data-toggle="tooltip" data-placement="right" data-original-title="美国时间"><i class="icon-info-sign"></i></a>';
}

function ScreenWidth(reduceHeight) {
    return parseInt(document.documentElement.clientHeight - reduceHeight);
}

var HtmlUtil = {
    /*1.用浏览器内部转换器实现html转码*/
    htmlEncode: function(html) {
            //1.首先动态创建一个容器标签元素，如DIV
            var temp = document.createElement("div");
            //2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(火狐，google支持)
            (temp.textContent != undefined) ? (temp.textContent = html) : (temp.innerText = html);
            //3.最后返回这个元素的innerHTML，即得到经过HTML编码转换的字符串了
            var output = temp.innerHTML;
            temp = null;
            return output;
        },
        /*2.用浏览器内部转换器实现html解码*/
        htmlDecode: function(text) {
            //1.首先动态创建一个容器标签元素，如DIV
            var temp = document.createElement("div");
            //2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
            temp.innerHTML = text;
            //3.最后返回这个元素的innerText(ie支持)或者textContent(火狐，google支持)，即得到经过HTML解码的字符串了。
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }
};

/**
* 压缩图片
* @param {} imgData 
* @param {} onCompress 
* @returns {} 
*/
function compressImg(imgData, maxHeight, onCompress) {
        maxHeight = maxHeight || 200;
        if (!imgData) {
            return false;
        };
        onCompress = onCompress || function() {};
        maxHeight = maxHeight || 100; //默认最大高度1000px
        var canvas = document.createElement('canvas');
        var img = new Image();
        img.src = imgData;
        img.onload = function() {
            if (img.height > maxHeight) { //按最大高度等比缩放
                img.width *= maxHeight / img.height;
                img.height = maxHeight;
            }
            var ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0, img.width, img.height);
            onCompress(canvas.toDataURL("image/jpeg"));
        }
};

(function (window, $) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(
                function () {
                    if (serializeObj[this.name]) {
                        if ($.isArray(serializeObj[this.name])) {
                            serializeObj[this.name].push(this.value);
                        } else {
                            serializeObj[this.name] = [
                                    serializeObj[this.name], this.value];
                        }
                    } else {
                        serializeObj[this.name] = this.value;
                    }
                });
        return serializeObj;
    };
})(window, jQuery);

function showImageLayer(imageUrlObj,imagelookUrl) {
    var imgUrl = encodeURI($(imageUrlObj).attr("imgUrl"));
    layer.open({
        type: 2,
        title: '查看图片',
        shadeClose: true,
        shade: 0.8,
        area: ['700px', '600px'],
        content: '/' + imagelookUrl + '?imgUrl=' + imgUrl //iframe的url
    });
}